"""
encoding: UTF-8
tim: 2024/11/29
title: 进度
message:

"""
import socket
import datetime
import requests


class Progres:
    def __init__(self):
        self.header = {'Content-Type': 'application/json'}
        self.sid = "bcdefghijklmnopqrstuvwxyz{23456789:101"
        self.server_url = "http://127.0.0.1:10801"
        self.robot_ip = socket.gethostbyname(socket.gethostname())

    def progres_insert(self, progres, flow_id, flow_name, robot_id):
        """
        进度信息
        :param progres:
        :param flow_id:
        :param flow_name:
        :param robot_id:
        :return:
        """
        json_data = {'sid': self.sid, 'progress': progres, 'flow_id': flow_id, 'flow_name': flow_name,
                     'robot_id': robot_id}
        value = requests.post(url=self.server_url + '/FlowRunningRecord', headers=self.header, json=json_data)
        if value.status_code == 200:
            return True
        else:
            return value.json()

    def get_robot_id(self):
        """
        获取设备在服务器中的 ROBOT_ID
        :return:
        """
        json_value = {'sid': self.sid, 'ip': self.robot_ip}
        robot_info_s = requests.post(url=self.server_url + '/WorkingCondition', json=json_value, headers=self.header)
        robot_info = robot_info_s.json()
        if robot_info['status'] == 0:
            return robot_info['data'][0]['robot_id']
        else:
            return None


def progres_pwa(value: str, flow_id: str, flow_name: str, robot_id: str = None):
    """
    进度执行信息 - RPA 流程使用
    flow_id 参数可以通过 /quest_list {sid, robot_id, flow_name} 获取, sid 参数为必要参数
    :param value: 进度信息，不需要添加时间
    :param flow_id:  流程ID【流程在工作台中的ID，如果是配置表的可以使用这个参数】
    :param flow_name:  流程名称【此处的名称需要打包的名称一致 EG: 测试流程.mrpa  flow_name = 测试流程】
    :param robot_id: 使用流程名称参数，该参数必须传递
    :return:
    """
    not_pro = [None, '', ' ', 'NULL', 'None', ',', '.']
    if str is None:
        return False
    if any([value.strip() == cell for cell in not_pro]):
        return False
    if not flow_id and not flow_name:
        return False
    if robot_id is None:
        robot_id = Progres().get_robot_id()
    tim = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    progress = f"{tim} {value}"
    result = Progres().progres_insert(progress, flow_id=flow_id, flow_name=flow_name, robot_id=robot_id)
    return result
